package gameos.android;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.appota.asdk.callback.TransactionStatusCallback;
import com.appota.asdk.commons.Constants;
import com.appota.asdk.inapp.InappAPI;
import com.appota.asdk.model.CardPayment;
import com.appota.asdk.model.TransactionResult;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.facebook.LoggingBehavior;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;

public class MainActivity extends AndroidApplication implements
		FacebookListener, IAPListener {
	/** Called when the activity is first created. */
	gameos.core.GameOS game;
	View gameView;

	// **** appota ****//
	InappAPI mIAP;
	static SharedPreferences mPreference;
	IAPListener mInappListener;
    Session.StatusCallback statusCallback = new SessionStatusCallback();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// getWindow().addFlags(6815872);
		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_FULLSCREEN
						| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

		// Create the layout
		RelativeLayout layout = new RelativeLayout(this);

		game = new gameos.core.GameOS();
		game.android = new AndroidFunctionImp(this);
		// Create the libgdx View
		gameView = initializeForView(game, false);

		// Add the libgdx view
		layout.addView(gameView);

		// Hook it all up
		setContentView(layout);

		mIAP = InappAPI.getInstance().setContext(this);
		mPreference = getSharedPreferences(Constants.PREF_ACCESS_TOKEN,
				Context.MODE_PRIVATE);
		
		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

        Session session = Session.getActiveSession();
        if (session == null) {
            if (savedInstanceState != null) {
                session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
            }
            if (session == null) {
                session = new Session(this);
            }
            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
            }
        }
	}

    @Override
    public void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    public void onStop() {
        super.onStop();
        Session.getActiveSession().removeCallback(statusCallback);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
        
		if (requestCode == Constants.INAPP_BANK_REQUEST_CODE
				&& resultCode == RESULT_OK) {
			String transactionId = data
					.getStringExtra(Constants.TRANSACTION_ID_KEY);
			Toast.makeText(this, transactionId, Toast.LENGTH_SHORT).show();
			mIAP.checkTransactionStatus(transactionId,
					new TransactionStatusCallback() {

						public void onTransactionSuccess(TransactionResult trans) {
							// TODO Auto-generated method stub
							MainActivity.this.onTransactionSuccess(
									trans.getMessage(), trans.getAmount(),
									trans.getCurrency(), trans.getErrorCode());
						}

						@Override
						public void onTransactionError(int errorCode,
								String message) {
							// TODO Auto-generated method stub
							MainActivity.this.onTransactionError(errorCode,
									message);
						}
					});
		} else if (requestCode == Constants.INAPP_SMS_REQUEST_CODE
				&& resultCode == Constants.RESULT_INAPP_SMS) {
			String transactionId = data
					.getStringExtra(Constants.TRANSACTION_ID_KEY);
			System.err.println(transactionId);
			mIAP.checkTransactionStatus(transactionId,
					new TransactionStatusCallback() {

						public void onTransactionSuccess(TransactionResult trans) {
							// TODO Auto-generated method stub
							MainActivity.this.onTransactionSuccess(
									trans.getMessage(), trans.getAmount(),
									trans.getCurrency(), trans.getErrorCode());
						}

						@Override
						public void onTransactionError(int errorCode,
								String message) {
							// TODO Auto-generated method stub
							MainActivity.this.onTransactionError(errorCode,
									message);
						}
					});
		} else if (requestCode == Constants.IN_APP_PAYPAL_REQUEST_CODE
				&& resultCode == RESULT_OK) {
			String transactionId = data
					.getStringExtra(Constants.TRANSACTION_ID_KEY);
			mIAP.checkTransactionStatus(transactionId,
					new TransactionStatusCallback() {

						public void onTransactionSuccess(TransactionResult trans) {
							// TODO Auto-generated method stub
							MainActivity.this.onTransactionSuccess(
									trans.getMessage(), trans.getAmount(),
									trans.getCurrency(), trans.getErrorCode());
						}

						@Override
						public void onTransactionError(int errorCode,
								String message) {
							// TODO Auto-generated method stub
							MainActivity.this.onTransactionError(errorCode,
									message);
						}
					});
		} else if (requestCode == Constants.INAPP_CARD_REQUEST_CODE
				&& resultCode == Constants.RESULT_INAPP_CARD) {
			CardPayment card = (CardPayment) data.getExtras().getSerializable(
					Constants.CARD_PAYMENT_DATA);

			mIAP.checkTransactionStatus(card.getTransactionId(),
					new TransactionStatusCallback() {

						public void onTransactionSuccess(TransactionResult trans) {
							// TODO Auto-generated method stub
							MainActivity.this.onTransactionSuccess(
									trans.getMessage(), trans.getAmount(),
									trans.getCurrency(), trans.getErrorCode());
						}

						@Override
						public void onTransactionError(int errorCode,
								String message) {
							// TODO Auto-generated method stub
							MainActivity.this.onTransactionError(errorCode,
									message);
						}
					});
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (event.getAction() == KeyEvent.ACTION_DOWN) {
			switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				gameView.setFocusable(true);
				gameView.requestFocus();
				gameView.onKeyDown(keyCode, event);
				return true;
			}
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onFeedRequest(String link, String name, String captain,
			String descript, String pictureUrl) {
		Session session = Session.getActiveSession();
        if (!session.isOpened() && !session.isClosed()) {
            session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
        } else {
            Session.openActiveSession(this, true, statusCallback);
        }
	}

	public static SharedPreferences getPreference() {
		return mPreference;
	}
	
	public static void saveString(final String key, final String value) {
		SharedPreferences.Editor editor = mPreference.edit();
		editor.putString(key, value);
		editor.commit();
	}
	
	public static void saveInt(final String key, final int value) {
		SharedPreferences.Editor editor = mPreference.edit();
		editor.putInt(key, value);
		editor.commit();
	}
	
	public static void saveBoolean(final String key, final boolean value) {
		SharedPreferences.Editor editor = mPreference.edit();
		editor.putBoolean(key, value);
		editor.commit();
	}
	
	public static String getString(final String key, final String defValue) {
		return mPreference.getString(key, defValue);
	}
	
	public static boolean getBoolean(final String key, final boolean defValue) {
		return mPreference.getBoolean(key, defValue);
	}
	
	public static int getInt(final String key, final int defValue) {
		return mPreference.getInt(key, defValue);
	}
	
	@Override
	public void callSmsPurchase() {
		// TODO Auto-generated method stub
		mIAP.inAppSMS(15000);
	}

	@Override
	public void callBankPurchase() {
		// TODO Auto-generated method stub
		mIAP.inAppBank(null, null, null);
	}

	@Override
	public void callPaypalPurchase() {
		// TODO Auto-generated method stub
		mIAP.inAppPaypal(null, null, null);
	}

	@Override
	public void callCardPurchase() {
		// TODO Auto-generated method stub
		mIAP.inAppCard(null, null, null);
	}

	@Override
	public void onTransactionSuccess(String message, String amount,
			String currentcy, int erroCode) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTransactionError(int errorCode, String message) {
		// TODO Auto-generated method stub

	}
	
    private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
        	
        }
    }
}